import { defineStore } from "pinia";
import $axios from '../utils/axios'
import { ElMessage } from 'element-plus'

export const useServicetypeStore = defineStore('servicetype', {
    state: () => {
        return {
            index: -1,
            dialogVisible: false,
            dialogTitle: '',
            treeData: [],
            fatherType: [],//服务大类
            allType: [],//所有小类,
            children: [],
            categorizedServices: {},// 分类的服务，键是服务类型ID，值是服务列表
            type: '',
            formdata: {
                id: -1,
            },
            typeB: {},
            typeS: {},
            cascaderOptions: [],// 用于存储级联选择器的选项 
            selectedOptions: [],// 选中的服务类别ID数组 
        }
    },
    actions: {
        //frontService:
        async selectFather() {//查找所有大类
            try {
                const path = '/serviceType/selectFather1'
                const { data: res } = await $axios.get(path)
                if (res.code === 200) {
                    this.fatherType = res.result
                    await this.fetchCategorizedServices()
                } else {
                    // 处理错误情况，比如抛出一个错误或设置一个错误状态  
                    console.error('Failed to load fatherType:', res);
                }
            } catch (error) {
                // 处理网络错误或其他异常  
                console.error('An error occurred:', error);
            }
        },
        async selectByFather(leaderId) {
            const path = '/serviceType/selectChildren1ByFather/' + leaderId
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.children = res.result
                // console.log(res.result)
                return res.result
            }
        },
        async fetchCategorizedServices() {
            const fetchPromises = this.fatherType.map(async (type) => {
                try {
                    const allChildren = await this.selectByFather(type.id)
                    this.categorizedServices[type.id] = allChildren//将获取到的服务列表存储到categorizedServices中
                    console.log(allChildren);
                } catch (error) {
                    console.error('Failed to fetch activities for type:', type.id, error);
                }
            });
            // 等待所有异步操作完成  
            await Promise.all(fetchPromises);
        },
        //ServiceType:
        async selectAllFather() {//查找所有大类
            try {
                const path = '/serviceType/selectAllFather'
                console.log('正在请求大类数据:', path);
                const { data: res } = await $axios.get(path)
                console.log('大类数据响应:', res);
                if (res.code === 200) {
                    this.fatherType = res.result || [];
                    console.log('成功获取大类数据:', this.fatherType);
                } else {
                    console.error('获取大类数据失败:', res);
                    ElMessage.error('获取服务类型数据失败: ' + (res.message || '未知错误'));
                }
            } catch (error) {
                console.error('获取大类数据时发生错误:', error);
                ElMessage.error('获取服务类型数据时发生错误: ' + (error.message || '未知错误'));
            }
        },
        async selectAllByFather(leaderId) {
            const path = '/serviceType/selectAllChildrenByFather/' + leaderId
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.children = res.result
                // console.log(res.result)
                return res.result
            }
        },
        async fetchChildrenForParents() {
            console.log('开始获取父类数据:', this.fatherType);
            if (!this.fatherType || this.fatherType.length === 0) {
                console.log('没有父类数据，尝试重新获取');
                await this.selectAllFather();
                if (!this.fatherType || this.fatherType.length === 0) {
                    console.error('无法获取父类数据');
                    ElMessage.error('无法获取服务类型数据');
                    return;
                }
            }

            try {
                console.log('开始获取子类数据');
                const fetchChildrenPromises = this.fatherType.map(async (father) => {
                    try {
                        if (!father || !father.id) {
                            console.error('父类数据无效:', father);
                            return;
                        }
                        console.log('正在获取父类的子项:', father.id);
                        const children = await this.selectAllByFather(father.id);
                        console.log('获取到的子类数据:', children);
                        if (!children) {
                            father.children = [];
                            father.hasChildren = false;
                            return;
                        }
                        father.children = children;
                        father.hasChildren = children.length > 0;
                    } catch (error) {
                        console.error(`获取ID为 ${father?.id} 的父类子项时出错:`, error);
                        father.children = [];
                        father.hasChildren = false;
                    }
                });

                await Promise.all(fetchChildrenPromises);
                this.treeData = this.fatherType;
                console.log('树形数据构建完成:', this.treeData);
            } catch (error) {
                console.error('获取子类数据时出错:', error);
                ElMessage.error('获取服务类型子类数据时发生错误: ' + (error.message || '未知错误'));
                this.treeData = this.fatherType.map(father => ({
                    ...father,
                    children: [],
                    hasChildren: false
                }));
            }
        },
        async selectAllChildren() {//所有小类
            const path = '/serviceType/selectAllChildren'
            const { data: res } = await $axios.get(path)
            if (res == 200) {
                this.allType = res.result
            }
            console.log(res);
        },
        pre4Order(typeBId, typeSId) {
            this.dialogVisible = true
            this.typeB = JSON.parse(JSON.stringify(typeBId))
            this.typeS = JSON.parse(JSON.stringify(typeSId))
            this.selectedOptions[0] = this.typeB
            this.selectedOptions[1] = this.typeS
            
            // 设置 formdata
            const user = JSON.parse(sessionStorage.getItem("user"))
            this.formdata = {
                id: -1,
                uId: user?.id,  // 使用 uId 而不是 userId
                typeBId: this.typeB.id,
                typeSId: this.typeS.id,
                reserveDate: null,
                serviceAddress: '',
                orderDetail: '',
                orderState: 0
            }
            console.log("预约订单数据：", this.formdata);
        },
        // 加载所有父类别（大类）  
        async loadFatherCategories() {
            try {
                const { data: res } = await $axios.get('/serviceType/selectFather1');
                this.cascaderOptions = res.result;
                // 如果需要，可以递归加载子类（这里假设不需要预先加载）  
            } catch (error) {
                console.error('Error loading father categories:', error);
            }
        },
        // 根据父类别ID加载子类别（小类）  
        async loadChildrenCategories(leaderId) {
            try {
                const { data: res } = await $axios.get('/serviceType/selectChildren1ByFather/' + leaderId);
                return res.result
            } catch (error) {
                console.error('Error loading children categories:', error);
                return [];// 加载失败时返回空数组
            }
        },
        async toOrder() {
            try {
                // 确保所有必要字段都存在
                if (!this.formdata.uId) {
                    ElMessage.warning('用户未登录')
                    return
                }

                // 构造请求数据，确保使用正确的字段名
                const orderData = {
                    uId: parseInt(this.formdata.uId),  // 确保使用 uId
                    typeBId: parseInt(this.formdata.typeBId),
                    typeSId: parseInt(this.formdata.typeSId),
                    reserveDate: this.formdata.reserveDate,
                    serviceAddress: this.formdata.serviceAddress,
                    orderDetail: this.formdata.orderDetail || '',
                    orderState: 0
                }

                // 打印发送的数据以便调试
                console.log('发送到后端的订单数据:', orderData)

                const { data: res } = await $axios.put('/serviceOrder/insert', orderData)
                if (res.code === 200) {
                    ElMessage.success('预约提交成功')
                    this.dialogVisible = false
                    this.formdata = {}
                } else {
                    ElMessage.error('订单创建失败：' + (res.msg || '未知错误'))
                }
            } catch (error) {
                console.error('订单提交错误:', error)
                ElMessage.error('订单提交失败：' + (error.response?.data?.msg || error.message || '未知错误'))
            }
        },
        pre4EditType(index, row) {
            this.index = index
            this.dialogVisible = true
            this.dialogTitle = '编辑服务父类别'
            this.formdata = JSON.parse(JSON.stringify(row))
        },
        pre4EditChildren(index, row) {
            this.index = index
            this.dialogVisible = true
            this.dialogTitle = '编辑服务子类别'
            this.formdata = JSON.parse(JSON.stringify(row))
        },
        async editType() {
            console.log(this.formdata);
            const path = '/serviceType/update'
            const { data: res } = await $axios.post(path, this.formdata)
            if (res.code === 200) {
                this.dialogVisible = false
                ElMessage({
                    message: '修改成功！',
                    type: 'success',
                })
            } else {
                this.dialogVisible = false
                ElMessage.error(res.msg)
            }
        },
        pre4Add(index, row) {
            this.index = index
            this.dialogVisible = true
            this.dialogTitle = '新增服务父类别'
        },
        pre4AddChildren(index, row) {
            this.index = index
            this.dialogVisible = true
            this.dialogTitle = '新增服务子类别'
            this.formdata.leaderId = row.id
        },
        async addType() {
            console.log(this.formdata);
            const path = '/serviceType/insert'
            const { data: res } = await $axios.put(path, this.formdata)
            if (res.code === 200) {
                this.dialogVisible = false
                ElMessage({
                    message: '添加成功！',
                    type: 'success',
                })
            } else {
                this.dialogVisible = false
                ElMessage.error(res.msg)
            }
        },
        save() {
            console.log(this.formdata.id);
            if (this.formdata.id == -1) {
                this.addType()
            } else {
                this.editType()
            }
        }
    }
})